package com.android.example.app3;

import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;

public class CursorImageAdapter extends RecyclerView.Adapter<CursorImageAdapter.ViewHolder> {
    private Cursor cursor;
    private Context context;
    private ContentResolver contentResolver;
    private ItemRemovedListener itemRemovedListener;


    // 构造函数，接受Cursor和Context

    // 构造函数设置监听器
    public void setItemRemovedListener(ItemRemovedListener listener) {
        this.itemRemovedListener = listener;
    }
    public CursorImageAdapter(Context context, Cursor cursor) {
        this.context = context;
        this.cursor = cursor;
        this.contentResolver = context.getContentResolver();
    }

    // 获取URI的方法，根据Cursor中的_ID列
    private Uri getUriFromCursor(Cursor cursor) {
        long id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID));
        return ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_image, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        if (!cursor.moveToPosition(position)) {
            return; // 如果无法移动到指定位置，则不执行任何操作
        }
        String imageName = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME));
        // 从Cursor中获取文件名称
        String[] parts = imageName.split("_", 2);  // 限制分割次数为1
        String fileNameBase = parts[0];  // imageName


        Uri uri = getUriFromCursor(cursor);
        // 使用Glide或Picasso加载图片
        Glide.with(context).load(uri).into(holder.imageView);
        holder.itemView.setOnLongClickListener(v -> {
            Intent shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.setType("image/*");
            shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
            context.startActivity(Intent.createChooser(shareIntent, "分享到"));
            return true; // Return true to indicate the event has been consumed
        });
        holder.itemView.setOnClickListener(v -> {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(uri, "image/*");
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            context.startActivity(intent);
        });
        // 设置删除按钮点击事件
        holder.deleteButton.setOnClickListener(v -> {
            int adapterPosition = holder.getAdapterPosition();
            if (adapterPosition == RecyclerView.NO_POSITION) return;
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle("正在删除图片操作")
                    .setMessage("是否删除图片")
                    .setPositiveButton("确认", (dialog, id) -> {
                        // 用户点击了确认按钮，你可以在这里执行相应操作
                        deleteImage(adapterPosition); // 调用删除方法
                        // 通知Activity数据已更改
                        if (itemRemovedListener != null) {
                            itemRemovedListener.onItemRemoved(fileNameBase);
                        }


                    })
                    .setNegativeButton("取消", (dialog, id) -> {
                        // 用户点击了取消按钮，你可以在这里执行相应操作
                        // 这里不需要做任何事情，因为用户选择了取消操作
                    })
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .show();

        });
    }

    // 新增删除方法
    private void deleteImage(int position) {
        if (cursor == null || !cursor.moveToPosition(position)) {
            return;
        }
        // 获取图片ID并构造URI
        long id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID));
        Uri uri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);

        // 执行删除操作
        int deletedRows = context.getContentResolver().delete(uri, null, null);
        if (deletedRows > 0) {
            // 删除成功，重新加载数据
            Toast.makeText(context, "图片已删除", Toast.LENGTH_SHORT).show();
            Cursor newCursor = context.getContentResolver().query(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    null, null, null, null
            );
            swapCursor(newCursor);
            close();

        } else {
            Toast.makeText(context, "删除失败", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public int getItemCount() {
        return cursor != null ? cursor.getCount() : 0;
    }

    // 释放Cursor资源的方法
    public void swapCursor(Cursor newCursor) {
        if (cursor != null) {
            cursor.close();
        }
        this.cursor = newCursor;
        if (newCursor != null) {
            notifyDataSetChanged();
        }
    }

    // 关闭Cursor并释放资源的方法
    public void close() {
        if (cursor != null) {
            cursor.close();
            cursor = null;
        }
    }


    public static class ViewHolder extends RecyclerView.ViewHolder {
        ImageView imageView;
        ImageView deleteButton; // 新增删除按钮

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.imageView);
            deleteButton = itemView.findViewById(R.id.deleteButton); // 绑定删除按钮
        }
    }
}